/**
 * 
 */
package pt.mleiria.web.controller;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import pt.mleiria.bo.GuestbookBO;
import pt.mleiria.bo.GuestbookCommand;
import pt.mleiria.vo.GuestbookVO;

/**
 * @author root
 *
 */
public class GuestbookController extends SimpleFormController {
	private GuestbookBO guestbookBO;
	
	/**
	 * @return the guestbookBO
	 */
	public GuestbookBO getGuestbookBO() {
		return guestbookBO;
	}

	/**
	 * @param guestbookBO the guestbookBO to set
	 */
	public void setGuestbookBO(GuestbookBO guestbookBO) {
		this.guestbookBO = guestbookBO;
	}

	/* (non-Javadoc)
	 * @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, org.springframework.validation.BindException)
	 */
	@Override
	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		GuestbookCommand guestbookCommand = (GuestbookCommand)command;
		if(guestbookCommand.getComment() != null && !guestbookCommand.getComment().equals("")){
			final String ip = request.getRemoteAddr();
			final String DATE_FORMAT_NOW = "yyyy-MM-dd HH:mm:ss";
			final Calendar cal = Calendar.getInstance();
		    final SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
		    final GuestbookVO guestbook = new GuestbookVO(guestbookCommand.getName(), guestbookCommand.getComment(), sdf.format(cal.getTime()), ip, false);
			guestbookBO.save(guestbook);
			request.getSession().setAttribute("obrigado", true);
		}
		
		return new ModelAndView("guestbook", "guestbookCommand", guestbookCommand);
	}

	/* (non-Javadoc)
	 * @see org.springframework.web.servlet.mvc.AbstractFormController#formBackingObject(javax.servlet.http.HttpServletRequest)
	 */
	@Override
	protected Object formBackingObject(HttpServletRequest request)
			throws Exception {
		List<GuestbookVO> comments = guestbookBO.getComments();
		/*
		boolean s = true;
		if(s)
			throw new IllegalArgumentException("teste123");
			*/
		request.getSession().setAttribute("comments", comments);
		return super.formBackingObject(request);
	}
	
	
	

}
